import { useConfigStore } from "@/store/config";
import { fetch } from '@tauri-apps/api/http';
import type { HttpVerb } from '@tauri-apps/api/http';
import type { ParamOptions } from './index.d';

/**
 *
 * @param url 请求基础函数
 * @param method
 * @param options
 * @returns
 */
export function request<T>(url: string, method: HttpVerb, options?: ParamOptions) {
  const configStore = useConfigStore()
  const config = configStore.gitlibConfig
  if (!url.startsWith('http')) {
    url = `${config.server}${url}`
  }

  if (options) {
    // 处理 query 中的数值类型
    if (options.query) {
      Object.keys(options.query).forEach(key => {
        const val = options?.query?.[key]
        switch(typeof val) {
          case 'number':
          case 'boolean':
            (options.query as any)[key] = val + '';
        }
      })
    }
  }
  return new Promise<T>((resolve, reason) => {
    console.log(`请求地址: ${url} ${method}`)
    console.log('请求参数: ', options)
    fetch<T>(url, {
      method,
      headers: {
        'PRIVATE-TOKEN': config.token
      },
      responseType: 1,
      ...options
    }).then(res => {
      if (res.ok) {
        resolve(res.data)
      } else {
        window.$message.error(`请求服务响应异常, 状态码[${res.status}]`)
        console.log('res:', res)
        reason(res)
      }
    }).catch(err => {
      window.$message.error('请求服务错误，详细信息请查看控制台')
      console.log('err:', err)
      reason(err)
    })
  })
}

/**
 * get请求
 * @param url
 * @param query
 * @returns
 */
export function get<T>(url: string, query?: Record<string, any>) {
  return request<T>(url, 'GET',{ query })
}
